package com.example.Handler;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.examplee.username.httpfrist_01.R;

public class HandlerpostdelayedActivity extends AppCompatActivity {
ImageView imageView;
    Button btnn;
    Handler mHandler=new Handler(new Handler.Callback() {
        @Override
        //截获消息,只会打印出1 ，会截获2的条件是 return true;
        public boolean handleMessage(Message msg) {
            Toast.makeText(getApplication(),"1",Toast.LENGTH_SHORT).show();
            return true;
        }
    }){

        @Override
        public void handleMessage(Message msg) {
            Toast.makeText(getApplication(),"2",Toast.LENGTH_SHORT).show();

            super.handleMessage(msg);
        }
    };
    int []images={R.drawable.img1,R.drawable.img2,R.drawable.img3};
    int index;
    MyRunable myRunable=new MyRunable();
    class MyRunable implements Runnable{

        @Override
        public void run() {
            index++;
            index=index%3;
            imageView.setImageResource(images[index]);
          mHandler.postDelayed(myRunable,1000);
//            mHandler.postAtTime(myRunable,1000);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handlerpostdelayed);
        imageView= (ImageView) findViewById(R.id.imgview1);
        mHandler.postDelayed(myRunable,1000);
        btnn= (Button) findViewById(R.id.btn_close);
        btnn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mHandler.removeCallbacks(myRunable);//移除Handler
                mHandler.sendEmptyMessage(1);//发送一个空的消息
            }
        });
//        mHandler.postAtTime(myRunable,1000);

    }
}
